let post_lock=false;
import { rootUrl,Version } from '@/utils/config.js'
export function https(opts, data = {}) {
	/* duplicate_submit 是否限制重复提交，默认否 */
    if (opts.duplicate_submit == undefined) {
        opts.duplicate_submit = false;
    }
    if (opts.show_loading == undefined) {
        opts.show_loading = true;
    }
	let duplicate_submit = opts.duplicate_submit;
    let show_loading = opts.show_loading;
	let httpDefaultOpts = {
        url: rootUrl + opts.url,
        data: data,
		method: opts.method,
        header: opts.method.toLowerCase() == 'get' ? {
			'X-Requested-With': 'XMLHttpRequest',
			"Accept": "application/json",
			"Content-Type": "application/json; charset=UTF-8"
		} : {
			'X-Requested-With': 'XMLHttpRequest',
            "Accept": "application/json",
			"Content-Type": "application/json; charset=UTF-8"
			// 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
		},
		dataType: 'json',

	}
    // httpDefaultOpts.header.version = Version;
	let token = uni.getStorageSync('token');
    // token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOi8vbG9jYWxob3N0Ojg4ODgvIiwiaWF0IjoxNzE5MzA2MzgwLCJkYXRhIjp7ImlkIjoxLCJ1c2VyX3R5cGUiOiJtZW1iZXIiLCJ0b2tlbiI6ImFkNTY5OGE2ZjFlYWM3YzMxYzk4NmI2NDEyYzEzY2VkIn0sInNjb3BlcyI6ImZyb250X2FjY2VzcyIsImV4cCI6MTcyMDYwMjM4MCwidHlwZSI6ImZyb250Q29kZSJ9.pTvO42eSKj707zzfZXKgkVydqm996vriVqaljOXVSJ8'
	if (token != undefined && token != null && token != '') {
		httpDefaultOpts.header.Authorization = token;
	}
	let promise = new Promise(function(resolve, reject) {
        // console.log('duplicate_submit',duplicate_submit)
        // console.log('post_lock',post_lock)
		if(duplicate_submit){
			if(post_lock){
				return false;
			}
			post_lock=true;
		}
        if(show_loading){
            uni.showLoading({})
        }
		uni.request(httpDefaultOpts).then(
			(res) => {
                setTimeout(function(){
				    post_lock=false;
				},1000)
                if (res.statusCode != 200 && res.statusCode != 256) {
                    uni.showToast({
                        title: res.data.msg || res.data.message ||'网络错误',
                        icon: 'none',
                        duration: 2000
                    });
                    reject(res.data)
                    return;
                }
				if (res.data.code == 50010 || res.data.code == 50011 || res.data.code == 50012 || res.data.code == 50013 || res.data.code == 50000) {
                    if (show_loading) {
                        uni.hideLoading();
                    }
					uni.clearStorageSync();
					uni.navigateTo({
                    	url: '/pages/login'
                    });
                    // uni.showToast({
                    //     title: res.data.msg,
                    //     icon: 'none',
                    //     duration: 2000
                    // });
                    // reject(res.data)
					return;
				}
				if(res.data.code == 0){
					uni.showToast({
						title: res.data.msg||'未知错误',
						icon: 'none',
						duration: 2000
					});
                    reject(res.data)
					return;
                } else if (res.data.code == 50062 || res.data.code == 50063 || res.data.code == 50064 || res.data.code == 50065){
					uni.showToast({
						title: res.data.msg,
						icon: 'none',
						duration: 2000
					});
					uni.clearStorageSync();
					setTimeout(function(){
						uni.navigateTo({
							url: '/pages/login'
						});
					},1000)

					return;
				}else if(res.data.code != 1){
					uni.showToast({
						title: res.data.msg,
						icon: 'none',
						duration: 2000
					});
                    reject(res.data)
					return;
                } else if (res.data.code == 1) {
                    if (show_loading) {
                        uni.hideLoading();
                    }
                }
				// if(res.statusCode == 401){
				// 	uni.clearStorageSync();
				// }
				resolve(res.data)
			}
		).catch(
			(response) => {
                if(show_loading){
                    uni.hideLoading();
                }
				post_lock=false;
				// console.log(response, '失败')
                if (response.errMsg.includes('timeout')) {
                    uni.showToast({
                        title: '网络请求超时！',
                        icon: 'none',
                        duration: 3000
                    });
                } else {
                    uni.showToast({
                        title: '网络连接失败，请稍后重试',
                        icon: 'none',
                        duration: 3000
                    });
                }
				reject(response)
			}
		)
	})

	return promise

}

export function https_upload(opts,filePath) {

    return new Promise((resolve, reject) => {

        uni.showLoading({})
        uni.uploadFile({
            filePath: filePath,
            name: opts.name,
            header: {
                Authorization: uni.getStorageSync('token')
            },
            url: rootUrl + opts.url,
            formData: {},
            success: (upRes) => {
                uni.hideLoading();
                let tmp_res = JSON.parse(upRes.data)
                if (tmp_res.code != 1) {
                    uni.showToast({ title: tmp_res.msg, icon: 'none' })
                    reject(tmp_res)
                    return false;
                }
                resolve(tmp_res);
            },
            fail: res => {
                uni.hideLoading();
                uni.showToast({ title: '上传失败', icon: 'none' })
                console.log('上传失败', res)
                reject(res)
            }
        });
    })
}